package com.github.ybq.core.style;

import com.github.ybq.core.sprite.Sprite;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.ThreeDimView;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;

public class RotatingCircle extends Sprite {

    private static String TAG = "RotatingCircle";
 

    private AnimatorValue mAnimatorValue;
    private float fraction;


    public RotatingCircle(){
        super();
        initAnimator();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        if (getRect() != null) {
            Rect bounds = clipSquare(getRect(),40);
            float w = bounds.getWidth() / 2f;
            float h = bounds.getHeight() / 2f;
            RectFloat rectFloat = new RectFloat(
                    bounds.getCenterX() - w,
                    bounds.getCenterY() - h,
                    bounds.getCenterX() + w,
                    bounds.getCenterY() + h);


            canvas.translate(rectFloat.getHorizontalCenter(),rectFloat.getVerticalCenter());
            ThreeDimView dimView = new ThreeDimView();

            if (fraction < 0.5){
                dimView.rotateY(fraction * 360);
            }else {
                dimView.rotateX((fraction - 0.5f) * 360);
            }


            dimView.applyToCanvas(canvas);

            canvas.translate(-rectFloat.getHorizontalCenter(),-rectFloat.getVerticalCenter());
            canvas.drawOval(rectFloat,mPaint);

            startAnimator();
        }
    }
    @Override
    public void startAnimator(){
        if (mAnimatorValue != null){
            if (!mAnimatorValue.isRunning()){
                mAnimatorValue.start();
            }
        }
    }
    private void initAnimator(){
        if (mAnimatorValue == null){
            mAnimatorValue = new AnimatorValue();
            mAnimatorValue.setLoopedCount(Animator.INFINITE);
            mAnimatorValue.setDuration(1200);
            mAnimatorValue.setDelay(100);
            mAnimatorValue.setCurveType(Animator.CurveType.LINEAR);
            mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    fraction = v;

                    if (getComponent() != null){
                        getComponent().invalidate();
                    }
                }
            });
        }
    }
    @Override
    public boolean isRunning() {
        if (mAnimatorValue != null){
            return mAnimatorValue.isRunning();
        }
        return super.isRunning();
    }
    @Override
    public void stopAnimator(){
        if (mAnimatorValue != null){
            if (mAnimatorValue.isRunning()){
                mAnimatorValue.stop();
            }
        }
    }
}

